package com.example.demo.mybatis.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mybatis.dot.input.PageParam;
import com.example.demo.mybatis.entity.TestQueryJsonV2;
import com.example.demo.mybatis.mapper.TestQueryJsonDaoV2;
import com.example.demo.mybatis.service.TestQueryJsonServiceV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * @author liyuncong
 * @version 1.0
 * @file TestQueryJsonServiceV2Impl
 * @brief TestQueryJsonServiceV2Impl
 * @details TestQueryJsonServiceV2Impl
 * @date 2022-11-17
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2022-11-17               liyuncong          Created
 */
@Service
public class TestQueryJsonServiceV2Impl
    extends ServiceImpl<TestQueryJsonDaoV2, TestQueryJsonV2>
    implements TestQueryJsonServiceV2 {

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Override
    public Page<TestQueryJsonV2> search(PageParam keywords) {
        Page<TestQueryJsonV2> page = new Page<>(10, 300);
        return this.baseMapper.findAll(page, keywords);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean create(TestQueryJsonV2 info) {
        try {
            List<String> list = new ArrayList<>();
            run(() -> insert(info), () -> list.add("qqqqqqqq"));

            if (list.isEmpty()) {
                throw new RuntimeException();
            }
            return false;
        } catch (RuntimeException e) {
            throw new RuntimeException();
        }
    }

    @Transactional(rollbackFor = Throwable.class)
    public boolean insert(TestQueryJsonV2 info) {
        return this.baseMapper.insert(info) > 0;
    }


    private void run(Callable<Boolean> action, Runnable consumer) {
        transactionTemplate.execute(status -> {
            try {
                if (!action.call()) {
                    consumer.run();
                }
            } catch (Exception ignored) {
                consumer.run();
            }
            return status;
        });
    }
}
